﻿using System;
using System.Collections.Generic;
using System.Linq;
using Atmk.WaterMeter.MIS.Base;
using Atmk.WaterMeter.MIS.Common;
using Atmk.WaterMeter.MIS.Commons;
using Atmk.WaterMeter.MIS.Commons.Interfaces.Logic;
using Atmk.WaterMeter.MIS.Commons.Utils;
using Atmk.WaterMeter.MIS.Datas;
using Atmk.WaterMeter.MIS.Models.ModelPuls;
using Atmk.WaterMeter.MIS.Tools;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace Atmk.WaterMeter.MIS.Controllers
{
    /// <summary>
    ///     分析模块接口
    /// </summary>
    [Authorize]
    public class AnalysisController : BaseApiController
    {
        private static ILogger<AnalysisController> _logger;
        private readonly TokenHelper _tokenHelper;

        /// <inheritdoc />
        public AnalysisController(
            ILogger<AnalysisController> logger,
            TokenHelper tokenHelper)
        {
            _logger = logger;
            _tokenHelper = tokenHelper;
        }

        /// <summary>
        ///     统计日/月用量统计列表
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost("/api/{X-Version}/Analysis/Dosage/Date")]
        public IActionResult GetDosageByDate([FromBody] dynamic obj)
        {
            var token = _tokenHelper.GetTokenByHttpContext();
            //验证用户信息

            try
            {
                return Ok(new
                {
                    errcode = 0,
                    msg = "ok"
                    //data = AnalysisMock.GetDosageByDate(obj,token.payload.id)
                });
            }
            catch (Exception e)
            {
                return Ok(new
                {
                    errcode = 1,
                    msg = $"获取数据错误,错误:{e.Message}"
                });
            }
        }

        /// <summary>
        ///     统计指定时间日均用量统计列表
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost("/api/{X-Version}/Analysis/Dosage/AvageDay")]
        public IActionResult GetDosageAvageDay([FromBody] dynamic obj)
        {
            var token = _tokenHelper.GetTokenByHttpContext();
            //验证用户信息

            try
            {
                return Ok(new
                {
                    errcode = 0,
                    msg = "ok"
                    //data = AnalysisMock.GetDosageAvageDay(obj, token.payload.id)
                });
            }
            catch (Exception e)
            {
                return Ok(new
                {
                    errcode = 1,
                    msg = $"获取数据错误,错误:{e.Message}"
                });
            }
        }

        /// <summary>
        ///     按主片区统计一定时间用量
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost("/api/{X-Version}/Analysis/Dosage/District")]
        public IActionResult GetDosageDistrict([FromBody] dynamic obj)
        {
            var token = _tokenHelper.GetTokenByHttpContext();
            //验证用户信息

            try
            {
                return Ok(new
                {
                    errcode = 0,
                    msg = "ok"
                    //data = AnalysisMock.GetDosageByDistrict(obj, token.payload.id)
                });
            }
            catch (Exception e)
            {
                return Ok(new
                {
                    errcode = 1,
                    msg = $"获取数据错误,错误:{e.Message}"
                });
            }
        }

        /// <summary>
        ///     按年统计各片区用量
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost("/api/{X-Version}/Analysis/Dosage/Year")]
        public IActionResult GetDosageYear([FromBody] dynamic obj)
        {
            var token = _tokenHelper.GetTokenByHttpContext();
            //验证用户信息

            try
            {
                return Ok(new
                {
                    errcode = 0,
                    msg = "ok"
                    //data = AnalysisMock.GetDosageDistrictYear(obj, token.payload.id)
                });
            }
            catch (Exception e)
            {
                return Ok(new
                {
                    errcode = 1,
                    msg = $"获取数据错误,错误:{e.Message}"
                });
            }
        }

        /// <summary>
        ///     按用量区间统计
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost("/api/{X-Version}/Analysis/Dosage/Interval")]
        public IActionResult GetDosageInterval([FromBody] dynamic obj)
        {
            var token = _tokenHelper.GetTokenByHttpContext();
            //验证用户信息

            try
            {
                return Ok(new
                {
                    errcode = 0,
                    msg = "ok"
                    //data = AnalysisMock.GetDosageInterval(obj, token.payload.id)
                });
            }
            catch (Exception e)
            {
                return Ok(new
                {
                    errcode = 1,
                    msg = $"获取数据错误,错误:{e.Message}"
                });
            }
        }

        /// <summary>
        ///     抄控指令成功率
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost("/api/{X-Version}/Analysis/Commands/SuccessRate")]
        public IActionResult GetSuccessRate([FromHeader] dynamic obj)
        {
            var token = _tokenHelper.GetTokenByHttpContext();
            //验证用户信息

            try
            {
                return Ok(new
                {
                    errcode = 0,
                    msg = "ok"
                    //data = AnalysisMock.GetCommandSuccessRate(obj, token.payload.id)
                });
            }
            catch (Exception e)
            {
                return Ok(new
                {
                    errcode = 1,
                    msg = $"获取数据错误,错误:{e.Message}"
                });
            }
        }


        /// <summary>
        ///  日用量统计
        /// </summary>

        [HttpPost("/api/{X-Version}/Analysis/GetDosageddList")]
        public IActionResult GetDosageddList([FromBody]dynamic obj)
        {
            var token = _tokenHelper.GetTokenByHttpContext();
            //验证用户信息
            DateTime searchDate = obj.searchDate;
            string searchDistrict = obj.searchDistrict.ToString();
            int pageIndex = obj.pageIndex;

            //根据用户获取片区编码集合进行匹配
            try
            {
                using (var _context = ContextBuilder.Build())
                {
                    var pageSize = _context.User.FirstOrDefault(m => m.Id.ToString() == token.payload.id).PageLines;
                    var MeterReadingRecord_Today = _context.MeterReadingRecord.Where(m => m.ReadTime.Date == searchDate.Date).GroupBy(m => m.CtdeviceId).Select(m => m.OrderByDescending(m1 => m1.ReadTime).FirstOrDefault());

                    var meter_ids = _context.Meter.Where(m=>m.DistrictId== searchDistrict).Select(m => m.CtdeviceId).ToArray();
                    var MeterReadingRecord_Ok = MeterReadingRecord_Today.Where(m => meter_ids.Contains(m.CtdeviceId)).ToList();

                    int count = MeterReadingRecord_Ok.Count();

                    var result = MeterReadingRecord_Ok.Skip((pageIndex - 1) * pageSize).Take(pageSize);
                    var CtdeviceIds = result.Select(m => m.CtdeviceId).ToList();

                    var districts = _context.District.Where(m => m.ProjectId == token.payload.areaid).ToList();
                    var meters = _context.Meter.Where(m=> CtdeviceIds.Contains(m.CtdeviceId)).ToList();
                    var ownerids = meters.Select(m => m.OwnerId).ToArray();
                    var owners = _context.Owner.Where(m => ownerids.Contains(m.Id)).ToList();

                    var file = new List<object>();
                    foreach (var item in result)
                    {
                        var meter = meters.FirstOrDefault(m => m.CtdeviceId == item.CtdeviceId);
                        if (meter==null)
                        {
                            continue;
                        }
                        var owner = owners.FirstOrDefault(m => m.Id == meter.OwnerId);
                        var district = districts.FirstOrDefault(m => m.Id == meter.DistrictId);
                        var ints = PublicMethod.ToIntArray(item.Value24, ',').Reverse().ToArray();
                        file.Add(new
                        {
                            district = district?.Name,
                            houseNumber = owner?.HouseNumber,
                            ownerName = owner?.Name,
                            meterNumber = meter?.MeterNumber,
                            readtime = item.ReadTime,
                            dd1 = 0,
                            dd2 = ints[1] - ints[0],
                            dd3 = ints[2] - ints[1],
                            dd4 = ints[3] - ints[2],
                            dd5 = ints[4] - ints[3],
                            dd6 = ints[5] - ints[4],
                            dd7 = ints[6] - ints[5],
                            dd8 = ints[7] - ints[6],
                            dd9 = ints[8] - ints[7],
                            dd10 = ints[9] - ints[8],
                            dd11 = ints[10] - ints[9],
                            dd12 = ints[11] - ints[10],
                            dd13 = ints[12] - ints[11],
                            dd14 = ints[13] - ints[12],
                            dd15 = ints[14] - ints[13],
                            dd16 = ints[15] - ints[14],
                            dd17 = ints[16] - ints[15],
                            dd18 = ints[17] - ints[16],
                            dd19 = ints[18] - ints[17],
                            dd20 = ints[19] - ints[18],
                            dd21 = ints[20] - ints[19],
                            dd22 = ints[21] - ints[20],
                            dd23 = ints[22] - ints[21],
                            dd24 = ints[23] - ints[22]
                        });
                    }

                    return Ok(new
                    {
                        errcode = 0,
                        msg = "ok",
                        data = new
                        {
                            total = count,
                            pageSize = 20,
                            list = file
                        }
                    });
                }
            }
            catch (Exception e)
            {
                _logger.LogError(e.Message);
                return Ok(new
                {
                    errcode = 1,
                    msg = $"获取数据错误,错误:{e.Message}"
                });
            }
        }

        /// <summary>
        ///  月用量统计
        /// </summary>
        [HttpPost("/api/{X-Version}/Analysis/GetDosagemmList")]
        public IActionResult GetDosagemmList([FromBody]dynamic obj)
        {
            var token = _tokenHelper.GetTokenByHttpContext();
            //验证用户信息
            DateTime searchDate = obj.searchDate;
            string searchDistrict = obj.searchDistrict.ToString();
            int pageIndex = obj.pageIndex;

            //根据用户获取片区编码集合进行匹配
            try
            {
                using (var _context = ContextBuilder.Build())
                {
                    var pageSize = _context.User.FirstOrDefault(m => m.Id.ToString() == token.payload.id).PageLines;
                    var SettlementDay_Month = _context.SettlementDay.Where(m => m.ReadTime.Month == searchDate.AddDays(1).Month && m.ReadTime.Year == searchDate.AddDays(1).Year).GroupBy(m => m.CtdeviceId).ToList();

                    var meter_ids = _context.Meter.Where(m => m.DistrictId == searchDistrict).Select(m => m.CtdeviceId).ToArray();
                    var SettlementDay_Ok = SettlementDay_Month.Where(m => meter_ids.Contains(m.Key)).ToList();

                    int count = SettlementDay_Ok.Count();

                    var result = SettlementDay_Ok.Skip((pageIndex - 1) * pageSize).Take(pageSize);
                    var CtdeviceIds = result.Select(m => m.Key).ToList();

                    var districts = _context.District.Where(m => m.ProjectId == token.payload.areaid).ToList();
                    var meters = _context.Meter.Where(m => CtdeviceIds.Contains(m.CtdeviceId)).ToList();
                    var ownerids = meters.Select(m => m.OwnerId).ToArray();
                    var owners = _context.Owner.Where(m => ownerids.Contains(m.Id)).ToList();

                    var file = new List<object>();
                    foreach (var item in result)
                    {
                        var meter = meters.FirstOrDefault(m => m.CtdeviceId == item.Key);
                        if (meter == null)
                        {
                            continue;
                        }
                        var owner = owners.FirstOrDefault(m => m.Id == meter.OwnerId);
                        var district = districts.FirstOrDefault(m => m.Id == meter.DistrictId);

                        dynamic obj_temp = new System.Dynamic.ExpandoObject();
                        obj_temp.district = district?.Name;
                        obj_temp.houseNumber = owner?.HouseNumber;
                        obj_temp.ownerName = owner?.Name;
                        obj_temp.meterNumber = meter?.MeterNumber;

                        foreach (var item1 in item)
                        {
                            ((IDictionary<string, object>)obj_temp).Add("dd"+item1.ReadTime.Day, item1.Dosage);
                            //item1.ReadTime.Day] = item1.Dosage;
                        }
                        file.Add(obj_temp);
                    }

                    return Ok(new
                    {
                        errcode = 0,
                        msg = "ok",
                        data = new
                        {
                            total = count,
                            pageSize = 20,
                            list = file
                        }
                    });
                }
            }
            catch (Exception e)
            {
                _logger.LogError(e.Message);
                return Ok(new
                {
                    errcode = 1,
                    msg = $"获取数据错误,错误:{e.Message}"
                });
            }
        }

        /// <summary>
        ///  年用量统计
        /// </summary>
        [HttpPost("/api/{X-Version}/Analysis/GetDosageyyyyList")]
        public IActionResult GetDosageyyyyList([FromBody]dynamic obj)
        {
            var token = _tokenHelper.GetTokenByHttpContext();
            //验证用户信息
            DateTime searchDate = obj.searchDate;
            string searchDistrict = obj.searchDistrict.ToString();
            int pageIndex = obj.pageIndex;

            //根据用户获取片区编码集合进行匹配
            try
            {
                using (var _context = ContextBuilder.Build())
                {
                    var pageSize = _context.User.FirstOrDefault(m => m.Id.ToString() == token.payload.id).PageLines;
                    var district = _context.District.Where(m => m.Id == searchDistrict).FirstOrDefault();
                    var SettlementDay_Month12 = _context.SettlementDay.Where(m => m.ReadTime.Year == searchDate.AddDays(1).Year).GroupBy(m => m.ReadTime.Month).ToList();
                    var owners = _context.Owner.Where(m => m.DistrictId == searchDistrict).OrderByDescending(m=>m.CreateTime);
                    var owner_ok = owners.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
                    int count = owners.Count();
                    var owner_ids = owner_ok.Select(m => m.Id).ToList();
                    var meters = _context.Meter.Where(m => owner_ids.Contains(m.OwnerId)).ToList();

                    var file = new List<object>();
                    foreach (var owner in owner_ok)
                    {
                        var meter_ctids = meters.Where(m => m.OwnerId == owner.Id).Select(m => m.CtdeviceId).ToArray();
                        dynamic obj_temp = new System.Dynamic.ExpandoObject();
                        obj_temp.district = district?.Name;
                        obj_temp.houseNumber = owner.HouseNumber;
                        obj_temp.ownerName = owner.Name;

                        foreach (var item_month in SettlementDay_Month12)
                        {
                            ((IDictionary<string, object>)obj_temp).Add("mm" + item_month.Key, item_month.Where(m=> meter_ctids.Contains(m.CtdeviceId)).Sum(m=>m.Dosage));
                        }
                        file.Add(obj_temp);
                    }

                    return Ok(new
                    {
                        errcode = 0,
                        msg = "ok",
                        data = new
                        {
                            total = count,
                            pageSize = 20,
                            list = file
                        }
                    });
                }
            }
            catch (Exception e)
            {
                _logger.LogError(e.Message);
                return Ok(new
                {
                    errcode = 1,
                    msg = $"获取数据错误,错误:{e.Message}"
                });
            }
        }

        /// <summary>
        ///  用量突增突减
        /// </summary>
        [HttpPost]
        public IActionResult GetDosagetztjList([FromBody]dynamic obj)
        {
            var token = _tokenHelper.GetTokenByHttpContext();
            //验证用户信息
            DateTime searchDate = obj.searchDate;
            string searchDistrict = obj.searchDistrict.ToString();
            int searchYValue = obj.searchYValue;
            int pageIndex = obj.pageIndex;
            //根据用户获取片区编码集合进行匹配
            try
            {
                using (var _context = ContextBuilder.Build())
                {
                    var pageSize = _context.User.FirstOrDefault(m => m.Id.ToString() == token.payload.id).PageLines;
                    var SettlementDay_Month = _context.SettlementDay.Where(m => m.ReadTime.Date >= searchDate.AddDays(-5).Date&& m.ReadTime.Date <= searchDate.AddDays(1).Date).GroupBy(m => m.CtdeviceId).ToList();
                    var SettlementDayTemp = new List<IGrouping<string, Entities.Models.SettlementDay>>();
                    foreach (var item in SettlementDay_Month)
                    {
                        if ((item.Max(m => m.Dosage) - item.Min(m => m.Dosage)) > searchYValue)
                        {
                            SettlementDayTemp.Add(item);
                        }
                    }

                    var meter_ids = _context.Meter.Where(m => m.DistrictId == searchDistrict).Select(m => m.CtdeviceId).ToArray();
                    var SettlementDay_Ok = SettlementDayTemp.Where(m => meter_ids.Contains(m.Key)).ToList();

                    int count = SettlementDay_Ok.Count();

                    var result = SettlementDay_Ok.Skip((pageIndex - 1) * pageSize).Take(pageSize);
                    var CtdeviceIds = result.Select(m => m.Key).ToList();

                    var districts = _context.District.Where(m => m.ProjectId == token.payload.areaid).ToList();
                    var meters = _context.Meter.Where(m => CtdeviceIds.Contains(m.CtdeviceId)).ToList();
                    var ownerids = meters.Select(m => m.OwnerId).ToArray();
                    var owners = _context.Owner.Where(m => ownerids.Contains(m.Id)).ToList();

                    var file = new List<object>();
                    foreach (var item in result)
                    {
                        var meter = meters.FirstOrDefault(m => m.CtdeviceId == item.Key);
                        if (meter == null)
                        {
                            continue;
                        }
                        var owner = owners.FirstOrDefault(m => m.Id == meter.OwnerId);
                        var district = districts.FirstOrDefault(m => m.Id == meter.DistrictId);

                        dynamic obj_temp = new System.Dynamic.ExpandoObject();
                        obj_temp.district = district?.Name;
                        obj_temp.houseNumber = owner?.HouseNumber;
                        obj_temp.ownerName = owner?.Name;
                        obj_temp.meterNumber = meter?.MeterNumber;
                        int i = 6;
                        foreach (var item1 in item)
                        {
                            ((IDictionary<string, object>)obj_temp).Add("dd" + i--, item1.Dosage);
                            //item1.ReadTime.Day] = item1.Dosage;
                        }
                        file.Add(obj_temp);
                    }

                    return Ok(new
                    {
                        errcode = 0,
                        msg = "ok",
                        data = new
                        {
                            total = count,
                            pageSize = 20,
                            list = file
                        }
                    });
                }
            }
            catch (Exception e)
            {
                _logger.LogError(e.Message);
                return Ok(new
                {
                    errcode = 1,
                    msg = $"获取数据错误,错误:{e.Message}"
                });
            }
        }

        /// <summary>
        ///  用量分析
        /// </summary>
        [HttpPost("/api/{X-Version}/Analysis/GetDosageanalyzeList")]
        public IActionResult GetDosageanalyzeList([FromBody]dynamic obj)
        {
            var token = _tokenHelper.GetTokenByHttpContext();
            //验证用户信息
            DateTime searchDate = obj.searchDate;
            string searchDistrict = obj.searchDistrict.ToString();
            int searchDosageStart = obj.searchDosageStart;
            int searchDosageEnd = obj.searchDosageEnd;
            int pageIndex = obj.pageIndex;

            //根据用户获取片区编码集合进行匹配
            try
            {
                using (var _context = ContextBuilder.Build())
                {
                    var pageSize = _context.User.FirstOrDefault(m => m.Id.ToString() == token.payload.id).PageLines;
                    var SettlementDay_Month = _context.SettlementDay.Where(m => m.ReadTime.Month == searchDate.AddDays(1).Month && m.ReadTime.Year == searchDate.AddDays(1).Year && m.Dosage >= searchDosageStart && m.Dosage <= searchDosageEnd).GroupBy(m => m.CtdeviceId).ToList();

                    var meter_ids = _context.Meter.Where(m => m.DistrictId == searchDistrict).Select(m => m.CtdeviceId).ToArray();
                    var SettlementDay_Ok = SettlementDay_Month.Where(m => meter_ids.Contains(m.Key)).ToList();

                    int count = SettlementDay_Ok.Count();

                    var result = SettlementDay_Ok.Skip((pageIndex - 1) * pageSize).Take(pageSize);
                    var CtdeviceIds = result.Select(m => m.Key).ToList();

                    var districts = _context.District.Where(m => m.ProjectId == token.payload.areaid).ToList();
                    var meters = _context.Meter.Where(m => CtdeviceIds.Contains(m.CtdeviceId)).ToList();
                    var ownerids = meters.Select(m => m.OwnerId).ToArray();
                    var owners = _context.Owner.Where(m => ownerids.Contains(m.Id)).ToList();

                    var file = new List<object>();
                    foreach (var item in result)
                    {
                        var meter = meters.FirstOrDefault(m => m.CtdeviceId == item.Key);
                        if (meter == null)
                        {
                            continue;
                        }
                        var owner = owners.FirstOrDefault(m => m.Id == meter.OwnerId);
                        var district = districts.FirstOrDefault(m => m.Id == meter.DistrictId);

                        dynamic obj_temp = new System.Dynamic.ExpandoObject();
                        obj_temp.district = district?.Name;
                        obj_temp.houseNumber = owner?.HouseNumber;
                        obj_temp.ownerName = owner?.Name;
                        obj_temp.meterNumber = meter?.MeterNumber;

                        foreach (var item1 in item)
                        {
                            ((IDictionary<string, object>)obj_temp).Add("dd" + item1.ReadTime.Day, item1.Dosage);
                            //item1.ReadTime.Day] = item1.Dosage;
                        }
                        file.Add(obj_temp);
                    }

                    return Ok(new
                    {
                        errcode = 0,
                        msg = "ok",
                        data = new
                        {
                            total = count,
                            pageSize = 20,
                            list = file
                        }
                    });
                }
            }
            catch (Exception e)
            {
                _logger.LogError(e.Message);
                return Ok(new
                {
                    errcode = 1,
                    msg = $"获取数据错误,错误:{e.Message}"
                });
            }
        }

        /// <summary>
        ///  用户缴费统计
        /// </summary>
        [HttpPost("/api/{X-Version}/Analysis/GetUserPayReportList")]
        public IActionResult GetUserPayReportList([FromBody]dynamic obj)
        {
            var token = _tokenHelper.GetTokenByHttpContext();
            //验证用户信息
            DateTime searchDate = obj.searchDate;
            string searchDistrict = obj.searchDistrict.ToString();
            decimal searchMoney1 = obj.searchMoney1;
            decimal searchMoney2 = obj.searchMoney2;
            int pageIndex = obj.pageIndex;

            //根据用户获取片区编码集合进行匹配
            try
            {
                using (var _context = ContextBuilder.Build())
                {
                    var pageSize = _context.User.FirstOrDefault(m => m.Id.ToString() == token.payload.id).PageLines;
                    var OrderDetail_Year = _context.OrderDetail.Where(m => m.CreateTime.Year == searchDate.AddDays(1).Year).GroupBy(m => m.OwnerId);
                    var OrderDetail_ok=OrderDetail_Year.Where(m => m.Sum(m1 => m1.Money) >= searchMoney1 && m.Sum(m1 => m1.Money) <= searchMoney2).ToList();

                    var owners_ids = OrderDetail_ok.Select(m => m.Key).ToArray();
                    var owners = _context.Owner.Where(m => owners_ids.Contains(m.Id)&& m.DistrictId == searchDistrict).ToList();

                    int count = owners.Count();
                    var result = owners.Skip((pageIndex - 1) * pageSize).Take(pageSize);
                    var district = _context.District.FirstOrDefault(m => m.Id == searchDistrict);

                    var file = new List<object>();
                    foreach (var owner in result)
                    {
                        var ownerTemp= _context.OrderDetail.Where(m => m.CreateTime.Year == DateTime.Now.Year && m.OwnerId == owner.Id).ToList();
                        dynamic obj_temp = new System.Dynamic.ExpandoObject();
                        obj_temp.ownerId = owner.Id;
                        obj_temp.district = district?.Name;
                        obj_temp.houseNumber = owner.HouseNumber;
                        obj_temp.ownerName = owner.Name;
                        obj_temp.balance = _context.OrderDetail.Where(m => m.OwnerId == owner.Id).Sum(m => m.Money);
                        obj_temp.PayCount = ownerTemp.Where(m => m.CostType == 0).Count();
                        obj_temp.LastPay = OrderDetail_ok.Where(m => m.Key == owner.Id).Sum(m => m.Where(m2 => m2.CostType ==0).OrderByDescending(m1=>m1.CreateTime).FirstOrDefault()?.Money);
                        obj_temp.LastMonthDosage = ownerTemp.Where(m =>  m.CreateTime.Month == DateTime.Now.AddMonths(-1).Month  && m.CostType == 1).Sum(m2 => m2.WaterVolume);
                        obj_temp.CurrentMonthDosage = ownerTemp.Where(m=>  m.CreateTime.Month == DateTime.Now.Month  && m.CostType==1).Sum(m2=>m2.WaterVolume);
                        //foreach (var item1 in item)
                        //{
                        //    ((IDictionary<string, object>)obj_temp).Add("dd" + item1.ReadTime.Day, item1.Dosage);
                        //    //item1.ReadTime.Day] = item1.Dosage;
                        //}
                        file.Add(obj_temp);
                    }

                    return Ok(new
                    {
                        errcode = 0,
                        msg = "ok",
                        data = new
                        {
                            total = count,
                            pageSize = 20,
                            list = file
                        }
                    });
                }
            }
            catch (Exception e)
            {
                _logger.LogError(e.Message);
                return Ok(new
                {
                    errcode = 1,
                    msg = $"获取数据错误,错误:{e.Message}"
                });
            }
        }

        /// <summary>
        ///  用户扣费统计
        /// </summary>
        [HttpPost("/api/{X-Version}/Analysis/GetUserFeeReportList")]
        public IActionResult GetUserFeeReportList([FromBody]dynamic obj)
        {
            var token = _tokenHelper.GetTokenByHttpContext();
            //验证用户信息
            DateTime searchDate = obj.searchDate;
            string searchDistrict = obj.searchDistrict.ToString();
            int pageIndex = obj.pageIndex;

            //根据用户获取片区编码集合进行匹配
            try
            {
                using (var _context = ContextBuilder.Build())
                {
                    var pageSize = _context.User.FirstOrDefault(m => m.Id.ToString() == token.payload.id).PageLines;
                    var OrderDetail_Month = _context.OrderDetail.Where(m => m.CreateTime.Year == searchDate.AddDays(1).Year&& m.CreateTime.Month == searchDate.AddDays(1).Month && m.CostType==1).ToList();
                
                    var owners_ids = OrderDetail_Month.GroupBy(m=>m.OwnerId).Select(m => m.Key).ToArray();
                    var owners = _context.Owner.Where(m => owners_ids.Contains(m.Id) && m.DistrictId == searchDistrict).ToList();

                    int count = owners.Count();
                    var result = owners.Skip((pageIndex - 1) * pageSize).Take(pageSize);
                    var district = _context.District.FirstOrDefault(m => m.Id == searchDistrict);

                    var file = new List<object>();
                    foreach (var owner in result)
                    {
                        var ownerTemp = _context.OrderDetail.Where(m => m.CreateTime.Year == DateTime.Now.Year && m.OwnerId == owner.Id).ToList();
                        dynamic obj_temp = new System.Dynamic.ExpandoObject();
                        obj_temp.ownerId = owner.Id;
                        obj_temp.district = district?.Name;
                        obj_temp.houseNumber = owner.HouseNumber;
                        obj_temp.ownerName = owner.Name;
                        obj_temp.CurrentMonthDosage = OrderDetail_Month.Where(m => m.OwnerId== owner.Id).Sum(m => m.WaterVolume);
                        obj_temp.CurrentMonthFee = OrderDetail_Month.Where(m => m.OwnerId == owner.Id).Sum(m => m.Money);
                        obj_temp.CurrentTodayDosage = OrderDetail_Month.Where(m => m.OwnerId == owner.Id && m.CreateTime.Date == searchDate.AddDays(1).Date).Sum(m => m.WaterVolume);
                        obj_temp.CurrentTodayFee = OrderDetail_Month.Where(m => m.OwnerId == owner.Id && m.CreateTime.Date == searchDate.AddDays(1).Date).Sum(m => m.Money);
                        obj_temp.CurrentLastTodayDosage = OrderDetail_Month.Where(m => m.OwnerId == owner.Id && m.CreateTime.Date == searchDate.Date).Sum(m => m.WaterVolume);
                        obj_temp.CurrentLastTodayFee = OrderDetail_Month.Where(m => m.OwnerId == owner.Id && m.CreateTime.Date == searchDate.Date).Sum(m => m.Money);

                        //foreach (var item1 in item)
                        //{
                        //    ((IDictionary<string, object>)obj_temp).Add("dd" + item1.ReadTime.Day, item1.Dosage);
                        //    //item1.ReadTime.Day] = item1.Dosage;
                        //}
                        file.Add(obj_temp);
                    }

                    return Ok(new
                    {
                        errcode = 0,
                        msg = "ok",
                        data = new
                        {
                            total = count,
                            pageSize = 20,
                            list = file
                        }
                    });
                }
            }
            catch (Exception e)
            {
                _logger.LogError(e.Message);
                return Ok(new
                {
                    errcode = 1,
                    msg = $"获取数据错误,错误:{e.Message}"
                });
            }
        }

        /// <summary>
        ///  日收费统计
        /// </summary>
        [HttpPost("/api/{X-Version}/Analysis/GetDaypayReportList")]
        public IActionResult GetDaypayReportList([FromBody]dynamic obj)
        {
            var token = _tokenHelper.GetTokenByHttpContext();
            //验证用户信息
            DateTime searchDate = obj.searchDate;
            string searchDistrict = obj.searchDistrict.ToString();
            int pageIndex = obj.pageIndex;

            //根据用户获取片区编码集合进行匹配
            try
            {
                using (var _context = ContextBuilder.Build())
                {
                    var pageSize = _context.User.FirstOrDefault(m => m.Id.ToString() == token.payload.id).PageLines;

                    var OrderDetail_LastDayDosage = _context.OrderDetail.Where(m => m.CreateTime.Date == searchDate.Date).ToList();
                    var OrderDetail_TodayDayDosage = _context.OrderDetail.Where(m =>  m.CreateTime.Date == searchDate.AddDays(1).Date).ToList();

                    //var OrderDetail_Year = _context.OrderDetail.Where(m => m.CreateTime.Date >= searchDate.Date&& m.CreateTime.Date <= searchDate.AddDays(1).Date).ToList();
                    var owners_ids = OrderDetail_TodayDayDosage.GroupBy(m => m.OwnerId).Select(m => m.Key).ToArray();
                    var owners = _context.Owner.Where(m => owners_ids.Contains(m.Id) && m.DistrictId == searchDistrict).ToList();

                    int count = owners.Count();
                    var result = owners.Skip((pageIndex - 1) * pageSize).Take(pageSize);
                    var district = _context.District.FirstOrDefault(m => m.Id == searchDistrict);

                    var file = new List<object>();
                    foreach (var owner in result)
                    {
                        dynamic obj_temp = new System.Dynamic.ExpandoObject();
                        obj_temp.ownerId = owner.Id;
                        obj_temp.district = district?.Name;
                        obj_temp.houseNumber = owner.HouseNumber;
                        obj_temp.ownerName = owner.Name;
                        obj_temp.balance = _context.OrderDetail.Where(m => m.OwnerId == owner.Id).Sum(m => m.Money);
                        obj_temp.PayCount = _context.OrderDetail.Where(m => m.OwnerId == owner.Id&& m.CostType == 0).Count();
                        obj_temp.LastPay = _context.OrderDetail.OrderByDescending(m1 => m1.CreateTime).FirstOrDefault()?.Money;
                        obj_temp.LastDayDosage = OrderDetail_LastDayDosage.Where(m => m.OwnerId == owner.Id && m.CostType == 1).Sum(m2 => m2.WaterVolume);
                        obj_temp.TodayDayDosage = OrderDetail_TodayDayDosage.Where(m => m.OwnerId == owner.Id && m.CostType == 1).Sum(m2 => m2.WaterVolume);
                        //foreach (var item1 in item)
                        //{
                        //    ((IDictionary<string, object>)obj_temp).Add("dd" + item1.ReadTime.Day, item1.Dosage);
                        //    //item1.ReadTime.Day] = item1.Dosage;
                        //}
                        file.Add(obj_temp);
                    }

                    return Ok(new
                    {
                        errcode = 0,
                        msg = "ok",
                        data = new
                        {
                            total = count,
                            pageSize = 20,
                            list = file
                        }
                    });
                }
            }
            catch (Exception e)
            {
                _logger.LogError(e.Message);
                return Ok(new
                {
                    errcode = 1,
                    msg = $"获取数据错误,错误:{e.Message}"
                });
            }
        }

        /// <summary>
        ///  月收费统计
        /// </summary>
        [HttpPost("/api/{X-Version}/Analysis/GetMonthpayReportList")]
        public IActionResult GetMonthpayReportList([FromBody]dynamic obj)
        {
            var token = _tokenHelper.GetTokenByHttpContext();
            //验证用户信息
            DateTime searchDate = obj.searchDate;
            string searchDistrict = obj.searchDistrict.ToString();
            int pageIndex = obj.pageIndex;

            //根据用户获取片区编码集合进行匹配
            try
            {
                using (var _context = ContextBuilder.Build())
                {
                    var pageSize = _context.User.FirstOrDefault(m => m.Id.ToString() == token.payload.id).PageLines;

                    var OrderDetail_TodayDayDosage = _context.OrderDetail.Where(m => m.CreateTime.Year == searchDate.AddDays(1).Year&& m.CreateTime.Month == searchDate.AddDays(1).Month).ToList();
                    var OrderDetail_LastDayDosage = _context.OrderDetail.Where(m => m.CreateTime.Year == searchDate.AddDays(1).Year && m.CreateTime.Month == searchDate.AddDays(1).AddMonths(-1).Month).ToList();

                    var OrderDetail_Year = _context.OrderDetail.Where(m => m.CreateTime.Year == searchDate.AddDays(1).Year).GroupBy(m => m.OwnerId);

                    var owners_ids = OrderDetail_Year.Select(m => m.Key).ToArray();
                    var owners = _context.Owner.Where(m => owners_ids.Contains(m.Id) && m.DistrictId == searchDistrict).ToList();

                    int count = owners.Count();
                    var result = owners.Skip((pageIndex - 1) * pageSize).Take(pageSize);
                    var district = _context.District.FirstOrDefault(m => m.Id == searchDistrict);

                    var file = new List<object>();
                    foreach (var owner in result)
                    {
                        var ownerTemp = _context.OrderDetail.Where(m => m.CreateTime.Year == DateTime.Now.Year && m.OwnerId == owner.Id).ToList();
                        dynamic obj_temp = new System.Dynamic.ExpandoObject();
                        obj_temp.ownerId = owner.Id;
                        obj_temp.district = district?.Name;
                        obj_temp.houseNumber = owner.HouseNumber;
                        obj_temp.ownerName = owner.Name;
                        obj_temp.balance = _context.OrderDetail.Where(m => m.OwnerId == owner.Id).Sum(m => m.Money);
                        obj_temp.PayCount = ownerTemp.Where(m => m.CostType == 0).Count();
                        obj_temp.LastPay = OrderDetail_Year.Where(m => m.Key == owner.Id).ToList().Sum(m => m.Where(m2 => m2.CostType == 0).OrderByDescending(m1 => m1.CreateTime).FirstOrDefault()?.Money);
                        obj_temp.LastMonthDosage = OrderDetail_LastDayDosage.Where(m => m.OwnerId == owner.Id && m.CostType == 1).Sum(m2 => m2.WaterVolume);
                        obj_temp.TodayMonthDosage = OrderDetail_TodayDayDosage.Where(m => m.OwnerId == owner.Id && m.CostType == 1).Sum(m2 => m2.WaterVolume);
                        //foreach (var item1 in item)
                        //{
                        //    ((IDictionary<string, object>)obj_temp).Add("dd" + item1.ReadTime.Day, item1.Dosage);
                        //    //item1.ReadTime.Day] = item1.Dosage;
                        //}
                        file.Add(obj_temp);
                    }

                    return Ok(new
                    {
                        errcode = 0,
                        msg = "ok",
                        data = new
                        {
                            total = count,
                            pageSize = 20,
                            list = file
                        }
                    });
                }
            }
            catch (Exception e)
            {
                _logger.LogError(e.Message);
                return Ok(new
                {
                    errcode = 1,
                    msg = $"获取数据错误,错误:{e.Message}"
                });
            }
        }


    }
}